﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using MyWeb.JwtAuthorization.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MyWeb.JwtAuthorization.Services
{
    public class JwtService:IJwtService
    {
        private JwtTokenOptions _JwtTokenOptions = null;
        public JwtService(IOptions<JwtTokenOptions> options)
        {
            this._JwtTokenOptions = options.Value;
        }

        /// <summary>
        /// JWT是个Token---
        /// 1   就是传递用户信息
        /// 2   加密钥---签名
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetToken(string name)
        {
            var claims = new[]
            {
                 new Claim("Name", name),
                 new Claim("id", "11"),
                 #region 为授权添加
                 new Claim(ClaimTypes.Name, "Eleven"),
                 new Claim("EMail", "57265177@qq.com"),
                 new Claim(ClaimTypes.Email, "xuyang@zhaoxiedu.net"),
                 new Claim("Account", "Administrator"),
                 new Claim("Age", "35"),
                 new Claim("Mobile", "18664876666"),
                 new Claim(ClaimTypes.Role,"Admin"),
                 new Claim("Role", "User"),//这个不能默认角色授权，动态角色授权
                 new Claim("Sex", "1")//各种信息拼装
	             #endregion
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._JwtTokenOptions.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: this._JwtTokenOptions.Issuer,//发行人
                audience: this._JwtTokenOptions.Audience,//授予人
                claims: claims,
                expires: DateTime.Now.AddSeconds(60 * 10),//10分钟有效期
                notBefore: DateTime.Now,//立即生效  DateTime.Now.AddMilliseconds(30),//30s后有效
                signingCredentials: creds
                );
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
    }
}
